<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<body>
		<button onclick="add()">添加</button>
		<table border="1">
			<thead>
				<tr>
					<th>大类</th>
					<th>小类</th>
					<th>件数</th>
					<th>单位</th>
					<th>描述</th>
					<th>操作</th>
				</tr>
			</thead>
			<tbody>
				
			</tbody>
		</table>
		<script type="text/javascript">
			//对象
			//匿名对象
			//对象里面有属性，属性有值。key:value，属性:值
			let arr = [
				{type1: "肉类", type2: "猪肉", count: 1, unit: "箱", desc: "无"},
				{type1: "肉类", type2: "猪肉", count: 2, unit: "箱", desc: "无"},
				{type1: "肉类", type2: "猪肉", count: 3, unit: "箱", desc: "无"},
				{type1: "肉类", type2: "猪肉", count: 4, unit: "箱", desc: "无"}
			];
			console.log(arr);
			
			//获取table对象
			let table = document.getElementsByTagName("table")[0];
			let tbody = table.getElementsByTagName("tbody")[0];
			// console.log(tbody);
			update();
			
			function add() {
				clear();
				arr.push({type1: "肉类", type2: "猪肉", count: 4, unit: "箱", desc: "无"});
				update();
			}
			
			/**
			 * 清除表格内容
			 */
			function clear() {
				let trs = tbody.children;
				for(let index in trs) {
					tbody.remove(trs[index]);
				}
				tbody = document.createElement("tbody");
				table.appendChild(tbody);
			}
			
			function update() {
				for(let index in arr) {
					// console.log(index);
					let item = arr[index];
					let tr = document.createElement("tr");
					tbody.appendChild(tr);
					let td = document.createElement("td");
					td.innerText = item.type1;
					tr.appendChild(td);
					td = document.createElement("td");
					td.innerText = item.type2;
					tr.appendChild(td);
					td = document.createElement("td");
					td.innerText = item.count;
					tr.appendChild(td);
					td = document.createElement("td");
					td.innerText = item.unit;
					tr.appendChild(td);
					td = document.createElement("td");
					td.innerText = item.desc;
					tr.appendChild(td);
					td = document.createElement("td");
					td.innerHTML = `
						<button>编辑</button>
						<button onclick="del(${index})">删除</button>
					`;
					tr.appendChild(td);
				}
			}
			
			function del(index) {
				console.log(index);
				arr.splice(index, 1);
				clear();
				update();
			}
		</script>
	</body>
</html>
